// pages/record/index.js
import API from "../../api/index";
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showstate:false,//是否本机构学生
    img_url: app.globalData.IMG_URL,
    winHeight: '2100rpx',
    month: '2020-02-27',//月报时间切换
    monthinfo: "",//月报时间正式显示
    array: [
      { value: '2018', name: '第一期 2018', mold: 1 },
      { value: '2018', name: '第二期 2018', mold: 2 },
      { value: '2019', name: '第一期 2019', mold: 1 },
      { value: '2019', name: '第二期 2019', mold: 2 },
      { value: '2020', name: '第一期 2020', mold: 1 },
      { value: '2020', name: '第二期 2020', mold: 2 },
      { value: '2021', name: '第一期 2021', mold: 1 },
      { value: '2021', name: '第二期 2021', mold: 2 },
    ],//学期日期选择模拟数据
    index: 2,//学期报默认选中的下标
    date: '2020-02-27',//日报时间切换
    datainfo: "",//日报时间正式显示
    newsvalue:'日报',//标识日报还是月报还是学期报，根据这个状态显示对应页面
    showupdate:false,//切换日报页面是否出现
    currentTab:0,
    newspaper:[
      {
        key: "日报",
        value:"daily",
        active:true
      },
      {
        key: "月报",
        value: "monthly",
        active: false
      },
      {
        key: "学期报",
        value: "term",
        active: false
      }
    ],
    //日报的列表
    lists:[
        {
          title:"课程",
          data:"1",
          englishname:"course",
          data:{
            icon:"../../static/kc_slices/0121@2x.png",
            name:"MONDAY 周一课程",
            course:[]
          }
        },
        {
          title: "食谱",
          data: "12",
          englishname: "menu",
          data: {
            icon: "../../static/dt_slices/01.png",
            name: "MONDAY 周一食谱",
            foods: []
          }
         }
        ,
        {
          title: "学习",
          data: "123",
          englishname: "menu",
          data: {
            icon: "../../static/dt_slices/01.png",
            name: "MONDAY 周一学习情况",
            readcount:0,
            gist:[],
            job:[]
          }
        },
        {
          title: "生活",
          englishname: "menu",
          data: {
            icon: "../../static/dt_slices/01.png",
            name: "MONDAY 周一在园情况",
            garden:{}
          }
        }

    ],
    //月报列表
    monthly: {
      icon: "../../static/kc_slices/0121@2x.png",
      name: "September 2019",
      capacity:{
        title:"1.知识及能力培养",
        content:''
      }
    },
    //学期报列表
    semester: {
      icon: "../../static/kc_slices/0121@2x.png",
      name: "第一期 2019",
      content:'',
    }
  },
  //获取到点击的下标
  getcurrentTab(e){
    console.log(e.currentTarget.dataset.currenttab)
    this.setData({
      currentTab: e.currentTarget.dataset.currenttab
    })

    //0-课程 1-食谱 2-学习
    if (this.data.currentTab == 0) {
      this._getCourses()
    } else if (this.data.currentTab == 1) {
      this._getcookbook()
    } else if (this.data.currentTab == 2) {
      this._getLearnings()
    } else if (this.data.currentTab == 3) {
      this._getGardens()
    }
  },
  // update日报
  updatedate(e){
    this.setData({
      showupdate:true
    })
    console.log(e.currentTarget.dataset.value);
  },
  //选中日报
  pitch(e){
    this.setData({
      showupdate: false,
    })
    for (var k = 0; k < this.data.newspaper.length;k++){
      if (e.currentTarget.dataset.value ==k){
        var active = "newspaper["+e.currentTarget.dataset.value+"].active";
        console.log(this.data.newspaper[k].key)
          this.setData({
            [active]:true,
            newsvalue: this.data.newspaper[k].key  //将状态改为当前选择：‘日报，月报，学期报’
          })
        console.log(this.data.newspaper[e.currentTarget.dataset.value])
      }else{
        var active = "newspaper[" + k + "].active";
        this.setData({
          [active]: false
        })
      }
    }
    if (e.currentTarget.dataset.value==0){//日报
      
    } else if (e.currentTarget.dataset.value==1){//月报
      this._getMonthreports()
    } else if (e.currentTarget.dataset.value == 2) {//学期报
      this._getTermreports()
    }
    console.log(e.currentTarget.dataset.value);
  },
  pitchfalse(e){
    if (e.currentTarget.dataset.value == '' || e.currentTarget.dataset.value == undefined){
      this.setData({
        showupdate: false,
      })
    }
  },
  //日报picker选中触发的方法
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    //把获取到的日期分割成数组，再拼接成ui图显示的样子。
    var split = e.detail.value.split("-");
    if (this.data.newsvalue=='日报'){
      var datainfo = "Date " + split[1] + "/" + split[2];
      console.log("datainfo::" + datainfo);
      this.setData({
        date: e.detail.value,
        datainfo: datainfo
      })
      //每次日期改变的时候，本周的第几天也要改变
      let newdate = new Date(e.detail.value)
      let nowDayOfWeek = newdate.getDay(); //今天本周的第几天
      this.week(nowDayOfWeek);
    } else if (this.data.newsvalue=='月报'){
      var month=this.monthfun(split[1]);
      var monthinfo = month+" " + split[0];
      console.log("datainfo::" + monthinfo);
      let monthlyNname ='monthly.name'
      this.setData({
        month: e.detail.value,
        monthinfo: monthinfo,
        [monthlyNname]:monthinfo
      })
    }
    if (this.data.currentTab == 0 && this.data.newsvalue == '日报') {
      this._getCourses()
    } else if (this.data.currentTab == 1 && this.data.newsvalue == '日报') {
      this._getcookbook()
    } else if (this.data.currentTab == 2 && this.data.newsvalue == '日报') {
      this._getLearnings()
    } else if (this.data.currentTab == 3 && this.data.newsvalue == '日报') {
      this._getGardens()
    } else if (this.data.newsvalue == '月报'){
      this._getMonthreports()
    } else if (this.data.newsvalue == '学期报'){
      this._getTermreports()
    }
  },
  monthfun(val){
    var month = "";
    if (val == "01" || val == "1") {
      month = "January"
    } else if (val == "02" || val == "2") {
      month = "February"
    } else if (val == "03" || val == "3") {
      month = "March"
    } else if (val == "04" || val == "4") {
      month = "April"
    } else if (val == "05" || val == "5") {
      month = "May"
    } else if (val == "06" || val == "6") {
      month = "June"
    } else if (val == "07" || val == "7") {
      month = "July"
    } else if (val == "08" || val == "8") {
      month = "August"
    } else if (val == "09" || val == "9") {
      month = "September"
    } else if (val== "10") {
      month = "October"
    } else if (val== "11") {
      month = "November"
    } else if (val== "12") {
      month = "December"
    }
    return month;
  },
  //学期报picker选中触发的方法
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value, )
    let semester = 'semester.name'
    let name = this.data.array[e.detail.value].name
    this.setData({
      index: e.detail.value,
      [semester]: name
    })
    this._getTermreports()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData.userInfo)
    var that = this
    // wx.getSystemInfo({
    //   success: function (res) {
    //     console.log(res)
    //     that.setData({
    //       winHeight: res.windowHeight - 29 //这是减去tab导航的高度
    //     });
    //   }
    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取用户信息
    this._getUsers()
    //每次进入页面的时候获得当前月份
    this.getDateline()
  },
  //每次进入页面的时候获得当前月份
  getDateline(){
    var now = new Date(); //当前日期
    var nowDayOfWeek = now.getDay(); //今天本周的第几天
    var nowDay = now.getDate(); //当前日
    var nowMonth = now.getMonth()+1; //当前月
    var nowYear = now.getYear(); //当前年
    nowYear += (nowYear < 2000) ? 1900 : 0;
    console.log(nowYear + '-' + nowMonth + '-' + nowDay);
    let date = nowYear + '-' + nowMonth + '-' + nowDay;
    this.setData({
      month: date,
      date: date
    })
    //月报-切割月份显示正确日期
    this.format(date);
    //日报-切割获取今天本周的第几天
    this.week(nowDayOfWeek)

  },
  //日报-切割获取今天本周的第几天
  week(nowDayOfWeek){
    let nowDayOfWeekChinese = ''
    if (nowDayOfWeek=='1'){//周一
      nowDayOfWeekChinese ="MONDAY 周一"
    } else if (nowDayOfWeek == '2') {//周二
      nowDayOfWeekChinese = "TUESDAY 周二"
    } else if (nowDayOfWeek == '3') {//周三
      nowDayOfWeekChinese = "WEDNESDAY 周三"
    } else if (nowDayOfWeek == '4') {//周四
      nowDayOfWeekChinese = "THURSDAY 周四"
    } else if (nowDayOfWeek == '5') {//周五
      nowDayOfWeekChinese = "FRIDAY 周五"
    } else if (nowDayOfWeek == '6') {//周六
      nowDayOfWeekChinese = "SATURDAY 周六"
    } else if (nowDayOfWeek == '0') {//周日
      nowDayOfWeekChinese = "WEEKDAY 周日"
    }
    let name0 = 'lists[0].data.name'//周几课程
    let name1 = 'lists[1].data.name'//周几食谱
    let name2 = 'lists[2].data.name'//周几学习情况
    let name3 = 'lists[3].data.name'//周几在园情况
    this.setData({
      [name0]: nowDayOfWeekChinese +'课程',
      [name1]: nowDayOfWeekChinese + '食谱',
      [name2]: nowDayOfWeekChinese + '学习情况',
      [name3]: nowDayOfWeekChinese + '在园情况'
    })
  },
  //一开进入页面改变data的显示方式
  format(data) {
    var split = data.split("-");
    var datainfo = "Date " + split[1] + "/" + split[2];
    console.log("datainfo::" + datainfo);
    var split2 = this.data.month.split("-");
    var month = this.monthfun(split2[1]);
    var monthinfo = month + " " + split2[0];
    let monthlyNname = 'monthly.name'
    this.setData({
      datainfo: datainfo,
      monthinfo: monthinfo,
      [monthlyNname]: monthinfo
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //第一步先完成导航tab切换样式
  swichNav(e) {
    var current = e.currentTarget.dataset.current
    this.setData({
      currentTab: current
    })
  },
  bindChange(e) {
    var current = e.detail.current
    if (current == '0') {
      this._getCourses()
      this.setData({
        winHeight: '2100rpx'
      })
    }else if (current == '1') {
      this._getcookbook()
      this.setData({
        winHeight: '2100rpx'
      })
    }else if (current == '2'){
      this._getLearnings()
      this.setData({
        winHeight: '1022rpx'
      })
    } else if (current == '3'){
      this._getGardens()
      this.setData({
        winHeight: '1022rpx'
      })
    }
    this.setData({
      currentTab: current
    })
    //小程序滚动到顶部
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  //日报-获取课程列表
  _getCourses(){
    console.log(this.data.date)
    // console.log("app.globalData.userInfo.classes[0]:"+app.globalData.userInfo.classes[0].id)
    if (app.globalData.userInfo.classes.length>0){
    let class_id = app.globalData.userInfo.classes[0].id
    API.getCourses(class_id, this.data.date).then(res => {
      console.log('获取课程数据', res.data.courses)
      let course = 'lists[0].data.course'
      //如果有数据
      if (res.code != 1000) {
        this.setData({
          [course]:res.data.courses
        })
      } else {
        this.setData({
          [course]: ''
        })
      }
    })
    }else{
      // this.notBound()//未绑定班级和学生
    }
  },
  //未绑定班级和学生
  notBound(){
    wx.showToast({
      title: '您还未绑定班级和学生',
      icon: 'none',
      duration: 2000
    })
  },
  //日报-获取食谱列表
  _getcookbook(){
    let that = this
    let { img_url } = that.data
    console.log("食谱")
    API.getRecipes(this.data.date).then(res=>{
      console.log('获取食谱', res)
      let course = 'lists[1].data.foods'
      //如果有数据
      if (res.code != 1000) {
        res.data.recipes.forEach(item => {
          let split = item.recipe_name.split('，')
          item.recipe_name=split
          item.images.forEach(img=>{
            if (img.image.indexOf("https://") == -1) {
              img.image = img_url + img.image
            }
          })
        })
      this.setData({
        [course]: res.data.recipes
      })
      }else{
        this.setData({
          [course]: ''
        })
      }
    })
  },
  //日报-获取学习列表
  _getLearnings() {
    console.log("学习")
    if (app.globalData.userInfo.students.length>0){
    let student_id = app.globalData.userInfo.students[0].id
    API.getLearnings(student_id,this.data.date).then(res => {
      //如果有数据
      if (res.code != 1000){
        console.log('获取学习', res)
        //阅读数量
        let readcount = 'lists[2].data.readcount'
        //今日作业
        let homework = 'lists[2].data.job'
        let homeworksplit =res.data.learning.homework.split('&')
        //知识要点
        let gist = 'lists[2].data.gist'
        let gistsplit =res.data.learning.knowledge.split('&')
        this.setData({
          [readcount]: res.data.learning.reading,
          [homework]:homeworksplit,
          [gist]: gistsplit
        })
      }else{//如果没有数据
        console.log('获取学习', res)
        //阅读数量
        let readcount = 'lists[2].data.readcount'
        //今日作业
        let homework = 'lists[2].data.job'
        //知识要点
        let gist = 'lists[2].data.gist'
        this.setData({
          [readcount]: '',
          [homework]: '',
          [gist]: ''
        })
      }
    })
    }else{
      // this.notBound()//未绑定班级和学生
    }
  },
  //日报-获取生活列表
  _getGardens() {
    let that = this
    let { img_url } = that.data
    console.log("学习")
    if (app.globalData.userInfo.students.length>0){
    let student_id = app.globalData.userInfo.students[0].id
    API.getGardens(student_id, this.data.date).then(res => {
      //如果有数据
      //阅读数量
      let garden = 'lists[3].data.garden'
      if (res.code != 1000) {
        res.data.garden.action_images.forEach(item => {
          if (item.image.indexOf("https://") == -1) {
             item.image = img_url + item.image
          }
        })
        this.setData({
          [garden]: res.data.garden
        })
      } else {//如果没有数据
        this.setData({
          [garden]: ''
        })
      }
    })
    }else{
      // this.notBound()//未绑定班级和学生
    }
  },
  //月报 
  _getMonthreports(){
    if (app.globalData.userInfo.students.length>0){
    let student_id = app.globalData.userInfo.students[0].id
    let content = 'monthly.capacity.content'
    API.getMonthreports(student_id, this.data.month).then(res=>{
      if (res.code != 1000) {
        this.setData({
          [content]: res.data.month_report.content
        })
      }else{
        this.setData({
          [content]: ''
        })
      }
    })
    } else {
      // this.notBound()//未绑定班级和学生
    }
  },
  _getTermreports(){
    this.data.array.forEach((item,i) => {
      if(i==this.data.index){
        let mold = this.data.array[i].mold
        let year = this.data.array[i].value
          if (app.globalData.userInfo.students.length > 0) {
            let student_id = app.globalData.userInfo.students[0].id
            let content = 'semester.content'
            API.getTermreports(student_id, year, mold).then(res => {
              if (res.code != 1000) {
                this.setData({
                  [content]: res.data.term_report.content
                })
              } else {
                this.setData({
                  [content]: ''
                })
              }
            })
          } else {
            // this.notBound()//未绑定班级和学生
          }
      }
    })
  },
  refresh(){
    this._getUsers()
  },
  //获取用户信息
  _getUsers() {
    let that = this
    API.getUsers().then(res => {
      let userInfo = res.data.user
      app.globalData.userInfo = userInfo
      that.setData({ userInfo })
      if(res.data.user.classes.length>0){
        this.setData({
          showstate:true
        })
      }else{
        this.setData({
          showstate:false
        })
      }
      console.log(this.data.showstate)
      //课程
      if (this.data.currentTab == 0) {
        this._getCourses()
      } else if (this.data.currentTab==1){
        this._getcookbook()
      } else if (this.data.currentTab==2){
        this._getLearnings()
      } else if (this.data.currentTab == 3) {
        this._getGardens()
      }
    })
  }
})